package encoder

import (
	"gitee.com/general252/gomedia/go-codec"
	"github.com/pion/rtp"

	aacRTP "gitee.com/general252/gomedia/go-rtsp/rtp"
)

type AACDecoder1 struct {
	SampleRate int

	SizeLength       int
	IndexLength      int
	IndexDeltaLength int
	Asc              []byte

	decoder *aacRTP.AACUnPacker
}

// Init initializes the decoder.
func (d *AACDecoder1) Init() error {
	d.decoder = aacRTP.NewAACUnPacker(d.SizeLength, d.IndexLength, d.Asc)
	return nil
}

func (d *AACDecoder1) Decode(pkt *rtp.Packet) ([][]byte, error) {

	var out [][]byte

	if err := d.Decode2(pkt, func(frame []byte) {
		out = append(out, frame)
	}); err != nil {
		return nil, err
	}

	return out, nil
}

func (d *AACDecoder1) Decode2(pkt *rtp.Packet, onFrame func(frame []byte)) error {
	payload := pkt.Payload
	if payload[0] != 0x00 || payload[1] != 0x10 {
		var frame []byte
		// 没有 AU-headers
		if payload[0] == 0xFF && payload[1] == 0xF1 {
			// adts
			frame = payload
		} else {
			var adts []byte
			if len(d.Asc) > 0 {
				adtsHdr, _ := codec.ConvertASCToADTS(d.Asc, len(payload)+7)
				adts = adtsHdr.Encode()
			}
			frame = append(adts, payload...)
		}

		onFrame(frame)

		return nil
	}

	data, err := pkt.Marshal()
	if err != nil {
		return err
	}

	d.decoder.OnFrame(func(frame []byte, timestamp uint32, lost bool) {
		onFrame(frame)
	})

	err = d.decoder.UnPack(data)
	return err
}
